package com.moji.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moji.common.entity.MyPage;
import com.moji.common.utils.PageUtil;
import com.moji.entity.GdArea;
import com.moji.entity.MjCompanyInfo;
import com.moji.entity.MjUser;
import com.moji.entity.dto.AddMjUserDto;
import com.moji.entity.dto.ModifyPasswordDto;
import com.moji.entity.dto.QueryUserDto;
import com.moji.entity.vo.MjUserVo;
import com.moji.mapper.MjCompanyInfoMapper;
import com.moji.mapper.MjUserMapper;
import com.moji.service.GdAreaService;
import com.moji.service.MjUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moji.util.CheckUtils;
import com.moji.util.IdGenerator;
import com.moji.util.MD5Util;
import com.moji.util.MoJiCommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 客户信息表 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-08-17
 */
@Service
public class MjUserServiceImpl extends ServiceImpl<MjUserMapper, MjUser> implements MjUserService {
    @Resource
    private MjCompanyInfoMapper mjCompanyInfoMapper;

    @Resource
    private GdAreaService gdAreaService;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public MyPage<MjUser> queryByPage(QueryUserDto dto) {
        LambdaQueryWrapper<MjUser> wrapper = new LambdaQueryWrapper<>();
        //创建时间倒叙
        if(ObjectUtil.isNotEmpty(dto.getUserType()))
        {
            wrapper.eq(MjUser::getUserType,dto.getUserType());
        }
        if(ObjectUtil.isNotEmpty(dto.getLoginId()))
        {
            wrapper.eq(MjUser::getLoginId,dto.getLoginId());
        }
        if(ObjectUtil.isNotEmpty(dto.getMobile()))
        {
            wrapper.like(MjUser::getMobile,dto.getMobile());
        }
        if(ObjectUtil.isNotEmpty(dto.getUserName()))
        {
            wrapper.like(MjUser::getUserName,dto.getUserName());
        }
        if(ObjectUtil.isNotEmpty(dto.getId()))
        {
            wrapper.eq(MjUser::getId,dto.getId());
        }
        if(ObjectUtil.isNotEmpty(dto.getUserCode()))
        {
            wrapper.like(MjUser::getUserCode,dto.getUserCode());
        }
        if(ObjectUtil.isNotEmpty(dto.getEmail()))
        {
            wrapper.like(MjUser::getEmail,dto.getEmail());
        }
        if(ObjectUtil.isNotEmpty(dto.getCompanyName()))
        {
            wrapper.like(MjUser::getCompanyName,dto.getCompanyName());
        }
        wrapper.orderByDesc(MjUser::getCreateTime);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MjUser> mjUserList = list(wrapper);
        if(ObjectUtil.isNotEmpty(mjUserList)){
            mjUserList.forEach(mjUserVo->{
                MjCompanyInfo mjCompanyInfo=mjCompanyInfoMapper.selectOne(new LambdaQueryWrapper<MjCompanyInfo>()
                        .eq(MjCompanyInfo::getCompanyCode,mjUserVo.getCompanyCode()));
                if(mjCompanyInfo !=null){
                    mjUserVo.setCompanyName(mjCompanyInfo.getCompanyName());
                    mjUserVo.setCompanyCode(mjCompanyInfo.getCompanyCode());
                    mjUserVo.setCompanyAddress(mjCompanyInfo.getCompanyAddress());
                    mjUserVo.setCompanyAddressDetail(mjCompanyInfo.getCompanyAddressDetail());
                    mjUserVo.setCompanyFoundTime(mjCompanyInfo.getCompanyFoundTime());
                    mjUserVo.setBusinessLicense(mjCompanyInfo.getBusinessLicense());
                    mjUserVo.setCompanyLegal(mjCompanyInfo.getCompanyLegal());
                    mjUserVo.setCompanyLegalMobile(mjCompanyInfo.getCompanyLegalMobile());
                    mjUserVo.setCompanyLinkMan(mjCompanyInfo.getCompanyLinkMan());
                    mjUserVo.setCompanyLinkPhone(mjCompanyInfo.getCompanyLinkPhone());
                    mjUserVo.setCompanyType(mjCompanyInfo.getCompanyType());
                }

            });
        }

        PageInfo<MjUser> info = new PageInfo<>(mjUserList);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public boolean delete(Long id) {
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("主键ID不能为空,请核查!");
        }
        return this.removeById(id);
    }

    @Override
    public boolean add(AddMjUserDto dto) {
        MjUser mjUserOld = this.getOne(new LambdaQueryWrapper<MjUser>()
                .eq(MjUser::getLoginId, dto.getLoginId()));
        if (mjUserOld != null) {
            throw new RuntimeException("用户已存在,请核查!");
        }
        //姓名不能为空
        if (StringUtils.isEmpty(dto.getUserName())) {
            throw new RuntimeException("用户姓名不能为空,请核查!");
        }
        //校验手机号码合法性
        if (StringUtils.isNotEmpty(dto.getMobile()) && !CheckUtils.isPhoneLegal(dto.getMobile())) {
            throw new RuntimeException("手机号码格式不合法,请核查!");
        }
        //校验邮箱合法性
        if (StringUtils.isNotEmpty(dto.getEmail()) && !CheckUtils.isEmailLegal(dto.getEmail())) {
            throw new RuntimeException("邮箱格式不合法,请核查!");
        }
        MjUser mjUser=new MjUser();
        BeanUtils.copyProperties(dto,mjUser);
        String code= idGenerator.idGenerator("KH");
        mjUser.setUserCode(code);
        String md5Password = MD5Util.getMd5("123456").toUpperCase();
        mjUser.setPassword(md5Password);
        mjUser.setPrOnOff(ObjectUtil.isNotEmpty(mjUser.getPrOnOff())?mjUser.getPrOnOff():1);

        //用户类型 userType 0 - 个人用户 1 - 企业用户
        if(dto.getUserType()==1){
            //自定义生成企业编码
            String companyCode= idGenerator.idGenerator("QY");
            MjCompanyInfo mjCompanyInfo=new MjCompanyInfo();
            BeanUtils.copyProperties(dto,mjCompanyInfo);
            mjCompanyInfo.setCompanyCode(companyCode);
            mjCompanyInfo.setCreateTime(new Date());
            mjCompanyInfo.setUpdateTime(new Date());
            mjCompanyInfo.setUpdateId(MoJiCommonUtils.getUserCode());
            mjCompanyInfo.setCreateId(MoJiCommonUtils.getUserCode());
            mjCompanyInfoMapper.insert(mjCompanyInfo);

            mjUser.setCompanyCode(companyCode);
            mjUser.setCompanyName(mjCompanyInfo.getCompanyName());
        }
        mjUser.setCreateId(MoJiCommonUtils.getUserCode());
        mjUser.setUpdateId(MoJiCommonUtils.getUserCode());
        mjUser.setCreateTime(new Date());
        mjUser.setUpdateTime(new Date());
        return this.save(mjUser);
    }

    @Override
    public boolean edit(AddMjUserDto dto) {
        //姓名不能为空
        if (StringUtils.isEmpty(dto.getUserName())) {
            throw new RuntimeException("用户姓名不能为空,请核查!");
        }
        //校验手机号码合法性
        if (StringUtils.isNotEmpty(dto.getMobile()) && !CheckUtils.isPhoneLegal(dto.getMobile())) {
            throw new RuntimeException("手机号码格式不合法,请核查!");
        }
        //校验邮箱合法性
        if (StringUtils.isNotEmpty(dto.getEmail()) && !CheckUtils.isEmailLegal(dto.getEmail())) {
            throw new RuntimeException("邮箱格式不合法,请核查!");
        }
        MjUser mjUser=this.getById(dto.getId());
        mjUser.setUpdateTime(new Date());
        mjUser.setUpdateId(MoJiCommonUtils.getUserCode());
        //用户类型 userType 0 - 个人用户 1 - 企业用户
        if(dto.getUserType()==1){
            MjCompanyInfo mjCompanyInfo=mjCompanyInfoMapper.selectOne(new LambdaQueryWrapper<MjCompanyInfo>()
                    .eq(MjCompanyInfo::getCompanyCode,dto.getCompanyCode()));
            Long id=mjCompanyInfo.getId();
            BeanUtils.copyProperties(dto,mjCompanyInfo);
            mjCompanyInfo.setId(id);
            mjCompanyInfo.setUpdateTime(new Date());
            mjCompanyInfo.setUpdateId(MoJiCommonUtils.getUserCode());
            mjCompanyInfoMapper.updateById(mjCompanyInfo);
        }
        return this.updateById(mjUser);
    }

    @Override
    public MjUserVo detail(Long id) {
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("主键ID不能为空,请核查!");
        }
        MjUserVo mjUserVo=new MjUserVo();
        //个人信息
        MjUser mjUser=this.getById(id);
        if (mjUser != null) {
            BeanUtils.copyProperties(mjUser,mjUserVo);
        }
        //企业信息
        MjCompanyInfo mjCompanyInfo=mjCompanyInfoMapper.selectOne(new LambdaQueryWrapper<MjCompanyInfo>()
                .eq(MjCompanyInfo::getCompanyCode,mjUser.getCompanyCode()));
        if(mjCompanyInfo !=null){
            mjUserVo.setCompanyName(mjCompanyInfo.getCompanyName());
            mjUserVo.setCompanyCode(mjCompanyInfo.getCompanyCode());
            mjUserVo.setSocietyCreditCode(mjCompanyInfo.getCompanyAddress());
            mjUserVo.setCompanyAddressDetail(mjCompanyInfo.getCompanyAddressDetail());
            mjUserVo.setCompanyFoundTime(mjCompanyInfo.getCompanyFoundTime());
            mjUserVo.setBusinessLicense(mjCompanyInfo.getBusinessLicense());
            mjUserVo.setCompanyLegal(mjCompanyInfo.getCompanyLegal());
            mjUserVo.setCompanyLegalMobile(mjCompanyInfo.getCompanyLegalMobile());
            mjUserVo.setCompanyLinkMan(mjCompanyInfo.getCompanyLinkMan());
            mjUserVo.setCompanyLinkPhone(mjCompanyInfo.getCompanyLinkPhone());
            mjUserVo.setCompanyType(mjCompanyInfo.getCompanyType());
            mjUserVo.setCompanyAddress(mjCompanyInfo.getCompanyAddress());
            String address = mjCompanyInfo.getCompanyAddress();
            StringBuilder stringBuilder=new StringBuilder();
            if(address.split(",")!=null&&address.split(",").length>0)
            {
                String[] split = address.split(",");

                for (int i = 0; i < split.length; i++) {
                    LambdaQueryWrapper<GdArea> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(GdArea::getAreaCode,split[i]);
                    String areaName = gdAreaService.getOne(wrapper1).getAreaName();
                    stringBuilder.append(areaName);

                }
                mjUserVo.setCompanyAddressName(stringBuilder.toString());
            }

        }
        return mjUserVo;
    }

    @Override
    public boolean resetPassword(Long id) {
        MjUser mjUser = this.getById(id);
        if (mjUser == null) {
            throw new RuntimeException("用户不存在,请核查!");
        }
        mjUser.setPassword(MD5Util.getMd5("123456").toUpperCase());
        return this.updateById(mjUser);
    }

    @Override
    public boolean modifyPassword(ModifyPasswordDto modifyPasswordDao) {
        String newPassword = modifyPasswordDao.getNewPassword();
        String oldPassword = modifyPasswordDao.getOldPassword();
        String md5NewPassword = MD5Util.getMd5(newPassword).toUpperCase();
        String md5OldPassword = MD5Util.getMd5(oldPassword).toUpperCase();
        LambdaQueryWrapper<MjUser> wrapper = new LambdaQueryWrapper();
        wrapper.eq(MjUser::getUserCode, modifyPasswordDao.getUserCode());
        MjUser mjUser = this.getOne(wrapper);
        if (mjUser == null) {
            throw new RuntimeException("用户不存在,请核查!");
        }
        if (mjUser.getPassword().equals(md5OldPassword)) {
            mjUser.setPassword(md5NewPassword);
        }
        return this.updateById(mjUser);
    }
}
